package com.definity.toolkit.web.taglib;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

public class SelectTag extends ComponentFormTag {

	private static final long serialVersionUID = 3628326498321754282L;

	private String list;
	private String itemLabel;
	private String itemValue;
	
	public SelectTag() {

	}
	
	@Override
	protected String getComponentName() {
		return "select";
	}

	public void setList(String list) {
		this.list = list;
	}

	public void setItemLabel(String itemLabel) {
		this.itemLabel = itemLabel;
	}

	public void setItemValue(String itemValue) {
		this.itemValue = itemValue;
	}

	@Override
	protected int doStartTag(FormTag formTag, StringBuilder html) throws JspException {
		super.doStartTag(formTag, html);

		return EVAL_BODY_INCLUDE; 
	}
	
	@Override
	protected String createStartTag(String name, String id, Object value) {
		return "<select id=\"" + id + "\" name=\"" + id + "\"" + createStyleClass("common_field") + ">";
	}

	@Override
	protected String createEndTag(String name, String id, Object value) throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		
		StringBuilder html = new StringBuilder();
		
		List<?> domainList = (List<?>) request.getAttribute(list);
		for (Object domain : domainList) {
			Object optionValue = getValue(domain, itemValue);
			
			html.append("<option value='");
			html.append(optionValue);
			html.append("'");

			if (value != null && value.equals(optionValue)) {
				html.append(" selected='selected'");
			}

			html.append(">");
			html.append(getValue(domain, itemLabel));
			html.append("</option>");
		}
		
		html.append("</select>");
		
		return html.toString();
	}

}
